package com.rocksea.checkservice;

import android.os.Handler;
import android.util.Log;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Arrays;

/**
 * Created by Mrw on 2017/8/19.
 *
 *
 */

public class CheckThread extends Thread
{

    private String adrress;
    private int port;
    private boolean exit = true;
    private WaitThread thread;
    private Handler handler;

    public CheckThread(String adrress,int port,Handler handler){
        this.adrress = adrress;
        this.port = port;
        this.handler = handler;
    }
    @Override
    public void run() {
        super.run();
            try
            {
                    DatagramSocket socket = new DatagramSocket();
                    SocketAddress address = new InetSocketAddress(adrress,port);
                    socket.connect(address);
                    UDPPackage udpPackage = getUdpPackage();
                    DatagramPacket packet = new DatagramPacket(udpPackage.bytes(),udpPackage.length());
                    thread = new WaitThread(socket,handler);
                    thread.start();
                while (exit)
                {
                    Log.d("send: ",Arrays.toString(udpPackage.bytes()));
                    socket.send(packet);
                    sleep(10*1000);
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
                handler.obtainMessage(UDPPackage.OFF_LINE).sendToTarget();
            }
    }
    public void exit()
    {
        exit = false;
        if (thread!=null){
            thread.exit();
            thread=null;
        }
    }

    private UDPPackage getUdpPackage() throws UnsupportedEncodingException {
        String machineId = "APP";
        String versionId = "V1.0.0";
        byte[] MachineId = machineId.getBytes("GB2312");
        byte[] VersionId = versionId.getBytes("GB2312");
        byte[] machinIdData = new byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
        byte[] versionIdData = new byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
        System.arraycopy(MachineId,0,machinIdData,0,MachineId.length);
        System.arraycopy(VersionId,0,versionIdData,0,VersionId.length);
        UDPPackage udpPackage = new UDPPackage();
        udpPackage.login(machinIdData,versionIdData);
        return udpPackage;

    }


    private static class WaitThread extends Thread
    {
        private DatagramSocket socket;
        private boolean exit = true;
        private Handler handler;
        private TimeThread timeThread;


        private WaitThread(DatagramSocket socket,Handler handler)
        {
            this.socket = socket;
            this.handler = handler;

        }


        @Override
        public void run()
        {
            super.run();
            try {
                if (socket != null)
                {
                    byte[] receivePacket = new byte[1024];
                    DatagramPacket packet = new DatagramPacket(receivePacket,receivePacket.length);
                    timeThread = new TimeThread(handler);
                    timeThread.start();
                    while (exit)
                    {
                        //开始计时 阻塞超过30秒 认为连接不上
                        socket.receive(packet);
                        byte[] data = packet.getData();
                        Log.i("receive:  ",Arrays.toString(data));
                        UDPPackage respond = UDPPackage.checkSumPackage(data,0);
                        if (respond!=null)
                         {
                            if (respond.cCommand == UDPPackage.JZ_RESPOND)
                            {
                                exit();
                                handler.obtainMessage(UDPPackage.ON_LINE).sendToTarget();
                                if (timeThread!=null)
                                    timeThread.stopTimeThread();
                            }
                        }
                        sleep(1000);
                    }
                }
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
                handler.obtainMessage(UDPPackage.OFF_LINE).sendToTarget();
            }
        }
        private void exit()
        {
            exit = false;
            if (timeThread!=null) {
                timeThread.stopTimeThread();
                timeThread = null;
            }

        }

        private static class TimeThread extends Thread{
            private Handler handler;
            private TimeThread(Handler handler)
            {
                this.handler = handler;
            }

            private boolean gono = true;

            private void stopTimeThread(){
                gono = false;
            }

            @Override
            public void run() {
                super.run();
                try {
                    int sec =0;
                    while (gono){
                        sec++;
                        Log.d("time: ",sec+"");
                        if (sec>=30)
                        {
                            gono = false;
                            handler.obtainMessage(UDPPackage.OFF_LINE).sendToTarget();
                        }
                        sleep(1000);
                    }
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }


    }
}
